<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航End -->

    <el-card>
      <!-- 警告 -->
      <el-alert
        :closable="false"
        show-icon
        type="warning"
        title="注意：只允许为第三级分类设置相关参数！"
      ></el-alert>
      <!-- 警告End -->

      <!-- 选择商品分类 -->
      <div class="select-opts">
        <el-row>
          <el-col>
            <span>选择商品分类: </span>
            <el-cascader
              expand-trigger="hover"
              :props="selectConfig"
              :options="catesList"
              v-model="selectedKeys"
              @change="selectedChange"
              clearable
            >
            </el-cascader>
          </el-col>
        </el-row>
      </div>
      <!-- 选择商品分类End -->

      <!-- 标签页 -->
      <el-tabs v-model="activeTabName" @tab-click="tabClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button
            type="primary"
            :disabled="disabledSwitch"
            size="medium"
            @click="addDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 添加参数的按钮End -->

          <!-- 动态参数表格 -->
          <el-table :data="dynParamsList" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, idx) in scope.row.attr_vals"
                  :key="item + idx"
                  closable
                  :disable-transitions="true"
                  @close="closedTag(idx, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.newInputVisible"
                  v-model="scope.row.newTagInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>

            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  class="el-icon-edit"
                  size="mini"
                  type="primary"
                  @click="editParamsInfo(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  class="el-icon-edit"
                  size="mini"
                  type="danger"
                  @click="delDataInfo(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 动态参数表格End -->
        </el-tab-pane>
        <!-- 添加动态参数面板End -->

        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="disabledSwitch"
            size="medium"
            @click="addDialogVisible = true"
            >添加属性</el-button
          >

          <!-- 静态属性表格 -->
          <el-table :data="staticPropsList" style="width: 100%" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, idx) in scope.row.attr_vals"
                  :key="item + idx"
                  closable
                  :disable-transitions="true"
                  @close="closedTag(idx, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.newInputVisible"
                  v-model="scope.row.newTagInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  class="el-icon-edit"
                  size="mini"
                  type="primary"
                  @click="editParamsInfo(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  class="el-icon-edit"
                  size="mini"
                  type="danger"
                  @click="delDataInfo(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 静态属性表格End -->
        </el-tab-pane>
        <!-- 静态属性面板End -->
      </el-tabs>
      <!-- 标签页 -->
    </el-card>

    <!-- 添加参数/添加属性对话框 -->
    <el-dialog
      :title="'添加' + this.dialogTitle"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 输入框 -->
      <el-form
        :model="addFormData"
        :rules="updateFormRules"
        ref="addFormBox"
        label-width="80px"
      >
        <el-form-item :label="this.dialogTitle" prop="cat_name">
          <el-input v-model="addFormData.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 输入框End -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAddFormData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加参数/添加属性对话框End -->

    <!-- 修改值对话框 -->
    <el-dialog
      :title="'修改' + this.dialogTitle"
      :visible.sync="updateDialogVisible"
      width="50%"
      @close="updateDialogClosed"
    >
      <!-- 输入框 -->
      <el-form
        :model="updateFormData"
        :rules="addFormRules"
        ref="updateDialogForm"
        label-width="80px"
      >
        <el-form-item :label="this.dialogTitle" prop="cat_name">
          <el-input v-model="updateFormData.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUpdateForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改值对话框End -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 分类列表
      catesList: [],
      // 动态参数列表
      dynParamsList: [],
      // 静态属性列表
      staticPropsList: [],
      // 选项数据配置
      selectConfig: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 选中的分类
      selectedKeys: [],

      // 激活的标签
      activeTabName: "many",

      // 添加参数&加属性对话框的显示
      addDialogVisible: false,
      // 修改参数对话框的显示
      updateDialogVisible: false,
      // 添加参数&加属性表单数据
      addFormData: {
        cat_name: "",
      },
      addFormRules: {
        cat_name: [
          { required: true, message: "此选项不能为空！", trigger: "blur" },
        ],
      },

      // 编辑表单数据
      updateFormData: {
        cat_name: "",
      },
      updateFormRules: {
        cat_name: [
          { required: true, message: "此选项不能为空！", trigger: "blur" },
        ],
      },
      cat_id: 0,
      attr_id: 0,

      // 展开行标签s
      dynamicTags: [],
      // 新输入的标签
      newTagInputValue: "",
    };
  },

  computed: {
    disabledSwitch() {
      return this.selectedKeys.length == 3 ? false : true;
    },
    curCatId() {
      return this.selectedKeys[this.selectedKeys.length - 1];
    },
    dialogTitle() {
      return this.activeTabName == "many" ? "动态参数" : "静态属性";
    },
  },

  created() {
    this.getCatesData();
  },

  methods: {
    async getCatesData() {
      let { data: res } = await this.$http("categories");
      if (res.meta.status != 200)
        return this.$message.error("获取商品分类失败!");
      this.$message.success("获取商品分类成功!");
      this.catesList = res.data;

      console.log(this.catesList);
    },
    // 选择项改变
    selectedChange(arrKeys) {
      // 判断是否选中了三级分类
      if (arrKeys.length !== 3) {
        this.selectedKeys = [];
        this.dynParamsList = [];
        this.staticPropsList = [];
        return;
      }

      // 获取参数
      this.getParamsList();
    },

    tabClick() {
      // 获取参数
      this.getParamsList();
    },

    // 获取动态参数数据列表
    async getParamsList() {
      if (this.selectedKeys.length !== 3) return;
      // 根据所选分类的id,和当前所处的面板,获取对应的数据列表
      let { data: res } = await this.$http(
        `categories/${this.curCatId}/attributes`,
        {
          params: { sel: this.activeTabName },
        }
      );
      if (res.meta.status != 200) return this.$message.error("获取参数失败!");
      this.$message.success("获取参数成功!");
      if (this.activeTabName == "many") {
        this.dynParamsList = res.data;
      } else {
        this.staticPropsList = res.data;
      }

      // 以" "分隔字符串
      res.data.forEach((item) => {
        if (!item.attr_vals) {
          item.attr_vals = [];
        } else {
          item.attr_vals = item.attr_vals.split(" ");
        }
        this.$set(item, "newInputVisible", false);
        this.$set(item, "newTagInputValue", "");
      });
    },

    // 关闭添加对话框
    addDialogClosed() {
      this.$refs.addFormBox.resetFields();
    },

    // 确定表单提交
    saveAddFormData() {
      // 验证表单
      this.$refs.addFormBox.validate(async (valid) => {
        if (!valid) return;

        let { data: res } = await this.$http.post(
          `categories/${this.curCatId}/attributes`,
          {
            attr_name: this.addFormData.cat_name,
            attr_sel: this.activeTabName,
          }
        );

        if (res.meta.status != 201)
          return this.$message.error(`添加${this.dialogTitle}失败`);
        this.$message.error(`添加${this.dialogTitle}成功`);
        // 重新获取列表数据
        this.getParamsList();
        // 关闭对话框
        this.addDialogVisible = false;
      });
    },

    // 修改值
    editParamsInfo(payload) {
      this.updateFormData.cat_name = payload.attr_name;
      this.cat_id = payload.cat_id;
      this.attr_id = payload.attr_id;
      this.updateDialogVisible = true;
    },
    // 确定修改值（上传）
    async saveUpdateForm() {
      let { data: res } = await this.$http.put(
        `categories/${this.cat_id}/attributes/${this.attr_id}`,
        {
          attr_name: this.updateFormData.cat_name,
          attr_sel: this.activeTabName,
        }
      );
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error(`修改${this.dialogTitle}失败！`);
      this.getParamsList();
      this.$message.success(`修改${this.dialogTitle}成功！`);
      this.updateDialogVisible = false;
    },
    updateDialogClosed() {
      // 重置表单数据
      this.$refs.updateDialogForm.resetFields();
    },
    // 删除数据
    async delDataInfo(payload) {
      this.$confirm(
        `此操作将永久删除该${this.dialogTitle}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          let { data: res } = await this.$http.delete(
            `categories/${payload.cat_id}/attributes/${payload.attr_id}`
          );
          if (res.meta.status !== 200)
            return this.$message.error(`删除${this.dialogTitle}失败！`);
          this.$message.success(`成功删除${this.dialogTitle}！`);
          this.updateDialogVisible = false;
          this.getParamsList();
        })
        .catch((error) => {
          this.$message.error(`已取消删除${this.dialogTitle}！`);
        });
    },

    // 删除某个标签
    async closedTag(idx, payload) {
      payload.attr_vals.splice(idx, 1);
      this.saveDataChangeReq(payload);
    },

    // 发送请求，提交保存到数据库
    async saveDataChangeReq(payload) {
      console.log(payload.attr_vals);
      let { data: res } = await this.$http.put(
        `categories/${payload.cat_id}/attributes/${payload.attr_id}`,
        {
          attr_name: payload.attr_name,
          attr_sel: payload.attr_sel,
          attr_vals: payload.attr_vals.join(" "),
        }
      );

      if (res.meta.status !== 200)
        return this.$message.error("添加新标签失败！");
      this.$message.success("添加新标签成功！");
      payload.attr_vals = res.data.attr_vals.split(" ");
      payload.newTagInputValue = "";
      payload.newInputVisible = false;
    },

    // 失去焦点
    handleInputConfirm(payload) {
      if (payload.newTagInputValue.trim().length == 0) {
        payload.newTagInputValue = "";
        payload.newInputVisible = false;
        return;
      }
      payload.attr_vals.push(payload.newTagInputValue);
      this.saveDataChangeReq(payload);
    },

    // 显示输入新标签的输入框
    showInput(payload) {
      payload.newInputVisible = true;
      // $nextTick方法的作用：当页面上元素被重新渲染之后，
      // 才会执行回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
  }, // Methods End
};
</script>

<style scoped>
.el-table,
.el-tabs,
.select-opts {
  margin-top: 15px;
}
.el-cascader {
  width: 30%;
}
.input-new-tag,
.button-new-tag,
.el-tag + .el-tag {
  margin: 5px;
}

.input-new-tag {
  width: 120px;
}
</style>